package com.qf.web.controller;

import cn.hutool.core.bean.BeanUtil;
import com.qf.aop.aspect.ApiOperationLog;
import com.qf.aop.aspect.ApiOperationLogTitle;
import com.qf.api.dto.ResetPasswordDTO;
import com.qf.api.dto.UserStatusDTO;
import com.qf.api.entity.SysUserEntity;
import com.qf.api.form.ChangePasswordForm;
import com.qf.api.form.UserForm;
import com.qf.api.form.UserProfileForm;
import com.qf.api.mybatis.page.BaseController;
import com.qf.api.mybatis.page.PageResult;
import com.qf.api.service.SysUserService;
import com.qf.api.vo.UserInfoVO;
import com.qf.api.vo.UserPageVO;
import com.qf.core.enums.common.BusinessTypeEnum;
import com.qf.core.response.ResponseResult;
import com.qf.core.utils.CustomExcelUtil;
import com.qf.minio.service.MinioService;
import com.qf.security.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

/**
 * @Author: sin
 * @Date: 2025/5/8 15:39
 * @Description:
 **/
@Slf4j
@RestController
@Tag(name = "03.用户接口", description = "用户管理相关接口")
@ApiOperationLogTitle("用户模块")
@RequestMapping("/admin/users")
public class UserController extends BaseController {
    @Resource
    private SysUserService userService;

    /**
     * 根据用户名、手机号、开启状态来获取分页用户信息
     **/
    @Operation(summary = "01.分页查询用户", description = "根据用户名、手机号、状态分页获取用户信息")
    @GetMapping
    public ResponseResult<PageResult<UserPageVO>> getUserPage(@RequestParam(value = "username", required = false) String username,
                                                              @RequestParam(value = "status", required = false) Integer status,
                                                              @RequestParam(value = "mobile", required = false) String mobile) {
        startPage();
        List<UserPageVO> userPageVoList = userService.getUserPage(username, mobile, status);
        return ResponseResult.success(getData(userPageVoList));
    }

    @Operation(summary = "02.新增用户", description = "创建一个新的用户")
    @ApiOperationLog(desc = "新增用户信息", businessType = BusinessTypeEnum.ADD)
    @PostMapping
    public ResponseResult<Boolean> save(@RequestBody @Valid UserForm userForm) {
        return isOk(userService.saveUser(userForm));
    }

    @Operation(summary = "03.修改用户", description = "根据用户 ID 修改用户信息")
    @ApiOperationLog(desc = "更新用户信息", businessType = BusinessTypeEnum.MODIFY)
    @PutMapping("/{id}")
    public ResponseResult<Boolean> update(@Parameter(description = "用户ID") @PathVariable Long id, @RequestBody UserForm userForm) {
        userForm.setId(id);
        return isOk(userService.updateUser(userForm));
    }


    /**
     * 根据ID删除用户,id通过,分割
     **/
    @Operation(summary = "04.删除用户", description = "根据 ID 集合批量删除用户")
    @ApiOperationLog(desc = "删除用户", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping
    public ResponseResult<Boolean> removeBatchByIds(@RequestBody List<Long> userIds) {
        return isOk(userService.removeBatchByIds(userIds));
    }

    @Operation(summary = "05.重置用户密码", description = "管理员根据用户ID重置用户密码")
    @ApiOperationLog(desc = "重置密码", businessType = BusinessTypeEnum.MODIFY)
    @PatchMapping("/reset-password")
    public ResponseResult<Boolean> resetPassword(
            @Parameter(description = "用户ID", required = true) @RequestBody ResetPasswordDTO resetPasswordDTO) {
        return isOk(userService.resetPassword(resetPasswordDTO));
    }

    @Operation(summary = "06.上传用户头像", description = "用户上传头像图片")
    @ApiOperationLog(desc = "上传用户头像", businessType = BusinessTypeEnum.UPLOAD)
    @PostMapping(value = "/{userId}/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult<Boolean> uploadAvatar(@Parameter(description = "用户Id") @PathVariable("userId") Long userId,
                                                @Parameter(description = "头像文件") @RequestPart("avatar") MultipartFile avatar) {
        return ResponseResult.success(userService.uploadAvatar(avatar, userId));
    }

    @Operation(summary = "07.获取当前登录用户信息", description = "获取当前登录用户的详细信息")
    @GetMapping("/profile/me")
    public ResponseResult<UserInfoVO> getUserInfo() {
        SysUserEntity user = SecurityUtils.getUserInfo().getUser();
        SysUserEntity currentUser = userService.selectUserById(user.getId());
        UserInfoVO userInfoVo = new UserInfoVO(user.getId(), user.getUsername(), user.getNickname(), user.getAvatar(), currentUser.getEmail(), currentUser.getMobile(), currentUser.getGender(), user.getRoles().get(0).getName(), currentUser.getContent(), currentUser.getCreateTime());
        return ResponseResult.success(userInfoVo);
    }

    @Operation(summary = "08.导出用户信息 Excel", description = "将用户信息导出为 Excel 文件")
    @ApiOperationLog(desc = "将用户信息全部导出到excel", businessType = BusinessTypeEnum.EXPORT)
    @GetMapping("/export")
    public ResponseEntity<byte[]> userInfoExcel(@Parameter(description = "导出文件名", example = "用户信息.xlsx") @RequestParam("fileName") String fileName) {
        List<SysUserEntity> list = userService.list();
        List<UserPageVO> data = BeanUtil.copyToList(list, UserPageVO.class);
        for (UserPageVO user : data) {
            user.setGenderStr(user.getGender() == 1 ? "男" : "女");
        }
        return CustomExcelUtil.exportExcel(fileName, data, UserPageVO.class);
    }

    @Operation(summary = "09.修改密码", description = "修改当前用户密码")
    @ApiOperationLog(desc = "修改当前用户密码", businessType = BusinessTypeEnum.MODIFY)
    @PatchMapping("/profile/password")
    public ResponseResult<Boolean> updateCurrentUserPassword(@RequestBody @Valid ChangePasswordForm form) {
        SysUserEntity userInfo = SecurityUtils.getUserInfo().getUser();
        return isOk(userService.updateCurrentUserPassword(userInfo,form.getOldPassword(),form.getNewPassword(), form.getConfirmPassword()));
    }

    @Operation(summary = "10.修改用户信息", description = "修改当前用用户信息")
    @ApiOperationLog(desc = "修改当前用户信息", businessType = BusinessTypeEnum.MODIFY)
    @PutMapping("/profile")
    public ResponseResult<Boolean> updateCurrentUserInfo(@RequestBody UserProfileForm form) {
        SysUserEntity userInfo = SecurityUtils.getUserInfo().getUser();
        return isOk(userService.updateCurrentUserInfo(userInfo.getId(), form));
    }

    @Operation(summary = "11.修改用户状态")
    @ApiOperationLog(desc = "修改用户状态", businessType = BusinessTypeEnum.MODIFY)
    @PatchMapping("/status")
    public ResponseResult<Boolean> updateUserStatus(@RequestBody UserStatusDTO statusDTO) {
        return isOk(userService.updateUserStatus(statusDTO.getId(),statusDTO.getStatus()));
    }

    @Operation(summary = "12.修改当前用户头像", description = "修改当前用户头像")
    @ApiOperationLog(desc = "修改当前用户头像", businessType = BusinessTypeEnum.MODIFY)
    @PostMapping(value = "/profile/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult<Boolean> uploadAvatar(@Parameter(description = "头像文件") @RequestPart("avatar") MultipartFile avatar) {
        Long userId = SecurityUtils.getUserInfo().getUser().getId();
        return ResponseResult.success(userService.uploadAvatar(avatar, userId));
    }
}
